﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;

namespace TrinityAPI.Base
{
    /// <summary>
    /// 本地缓存帮助类
    /// </summary>
    public class CacheHelper : ICache
    {
        public CacheHelper()
        {

        }

        public CacheHelper(string connString)
        {
            if (!string.IsNullOrWhiteSpace(connString))
            {
                DbConnectionStringBuilder configs = new DbConnectionStringBuilder();
                try
                {
                    configs.ConnectionString = connString;
                    foreach (string key in configs.Keys)
                    {
                        //set options
                        //string config = configs[key] as string;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Cannot configure cache with an invalid connection string." + ex.Message);
                }
            }
        }

        public object Get(string key)
        {
            return HttpRuntime.Cache.Get(key);
        }

        public void Set(string key, object value)
        {
            HttpRuntime.Cache.Insert(key, value);
        }

        public void Set(string key, object value, int timeout)
        {
            HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(timeout), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        public void Remove(string key)
        {
            HttpRuntime.Cache.Remove(key);
        }

        public void RemoveAll()
        {
            List<string> keys = new List<string>();
            IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }
            foreach(string key in keys)
            {
                HttpRuntime.Cache.Remove(key);
            }
        }
    }
}
